﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.SystemConfig.DataAccess;
using Microsoft.Web.UI.WebControls;
using System.Data;
using Web.SystemConfig.Services;
using System.Web;
using DreamBuilder.Common;
using DreamBuilder.Core.Message;
using DreamBuilder.UI.UserControls;
using DreamBuilder.Core;



namespace Web.SystemConfig.Business
{
    public class BUSAuth_Org_User : BusinessBase, IAuth_Org_User
    {
        DALAuth_Org_User dal;
        public BUSAuth_Org_User()
        {
            dal = new DALAuth_Org_User();
        }

        #region 生成树

        private DataTable dtOrg;

        public DataTable DtOrg
        {
            get
            {
                if (dtOrg == null)
                {
                    dtOrg = dal.GetAllOrgData();
                }
                return dtOrg;
            }
        }

        public void CreateTree(TreeView tree)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID is null ");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                else
                {
                    DataRow rootDr = arrDr[0];
                    TreeNode root = new TreeNode();
                    root.ID = rootDr["ORG_ID"].ToString();
                    root.Text = rootDr["ORG_Name"].ToString() + "(" + rootDr["usercount"].ToString() + ")";
                    string url = "../SystemConfig/Auth_Org_User.aspx?Parent_ID=" + rootDr["ORG_ID"].ToString();
                    root.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    tree.Nodes.Add(root);
                    AddChildNode(root, rootDr["ORG_ID"].ToString());
                }
            }
        }

        private void AddChildNode(TreeNode root, string parentID)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID='" + parentID + "'");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                foreach (DataRow dr in arrDr)
                {
                    TreeNode child = new TreeNode();
                    child.ID = dr["ORG_ID"].ToString();
                    child.Text = dr["ORG_Name"].ToString() + "(" + dr["usercount"].ToString() + ")";
                    string url = "../SystemConfig/Auth_Org_User.aspx?Parent_ID=" + dr["ORG_ID"].ToString();
                    child.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    root.Nodes.Add(child);
                    AddChildNode(child, dr["ORG_ID"].ToString());
                }
            }
        }

        #endregion

        public void RefreshChildData(UCChild UCChildEdit, DataTable dataTable)
        {
            if (dataTable != null)
            {
                foreach (DataRow dr in dataTable.Rows)
                {
                    if (dr.RowState != DataRowState.Deleted)
                    {
                        DataTable dtUserInfo = dal.GetUserInfo(dr["User_ID"].ToString());
                        dr["Login_ID"] = dtUserInfo.Rows[0]["Login_ID"];
                        dr["User_Name"] = dtUserInfo.Rows[0]["User_Name"];
                        dr["Can_Login"] = dtUserInfo.Rows[0]["Can_Login"];
                        dr["User_Status"] = dtUserInfo.Rows[0]["Status_ID"];
                        dr["P_Auth_ORG_User__User_Status"] = dtUserInfo.Rows[0]["statusName"];
                    }
                }
                UCChildEdit.Refresh(ref dataTable);
            }
        }

        public DataTable SelectRolesByOrgID(string OrgID)
        {
            return dal.SelectRolesByOrgID(OrgID);
        }

        public ResultInfo SaveData(DataSet dsInfo, System.Web.UI.WebControls.CheckBoxList checkBoxList, string OrgID)
        {
            //先处理user表中orgid
            DataTable dt = dsInfo.Tables[0].Copy();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                {
                    dr.RejectChanges();
                    dr["RowStatus"] = (int)ROWSTATUS.STATUS_Delete;
                }
                ROWSTATUS nRowStatus = (ROWSTATUS)System.Convert.ToInt32(dr["RowStatus"].ToString().Trim());
                switch (nRowStatus)
                {
                    case ROWSTATUS.STATUS_Add:
                        dal.InsertOrgUserUpdateUser(dr);
                        break;
                    case ROWSTATUS.STATUS_Delete:
                        dal.DeleteOrgUserUpdateUser(dr);
                        break;
                }
            }
            //再保存
            ResultInfo result = base.Save(dsInfo);
            if (result.bSuccess == false)
            {
                return result;
            }
            try
            {
                #region 保存部门角色
                string roleID = string.Empty;
                string hasRoleSave = "";
                foreach (System.Web.UI.WebControls.ListItem li in checkBoxList.Items)
                {
                    //get the saved status
                    hasRoleSave = li.Value.Substring(0, 1);
                    //get the roleID
                    roleID = li.Value.Remove(0, 2);

                    //add the UserRole
                    if (hasRoleSave == "0" && li.Selected)
                    {
                        dal.InsertUserRole(OrgID, roleID);
                    }
                    //delete the UserRole
                    else if (hasRoleSave == "1" && (!li.Selected))
                    {
                        dal.DeleteUserRole(OrgID, roleID);
                    }
                }
                #endregion


            }
            catch (System.Data.SqlClient.SqlException sqlErr)
            {
                result.bSuccess = false;
                result.ErrorID = sqlErr.Number.ToString();
            }
            catch (System.Exception err)
            {
                result.bSuccess = false;
                result.ErrorDesc = err.Message;
            }
            return result;
        }


        public bool CheckUserDepartment(string Uesr_ID, string ORG_ID)
        {
            if (!string.IsNullOrEmpty(Uesr_ID) && !string.IsNullOrEmpty(ORG_ID))
            {
                return dal.CheckUserDepartment(Uesr_ID, ORG_ID);
            }
            else
            {
                return false;
            }
        }

    }
}
